from django.http import HttpResponse, HttpResponseBadRequest

from fb.auth import permissions

try:
  import json as simplejson
except ImportError:
  from django.utils import simplejson   # Python 2.5 fallback

import hashlib
import hmac

def process_update(request):
  # GET requests are for verification from Facebook's servers
  if request.method == "GET":
    token = request.GET["hub.verify_token"]
    challenge = request.GET["hub.challenge"]
    return HttpResponse(challenge)

  # Make sure the content type is correct  
  if request.META['CONTENT_TYPE'] != 'application/json':
    return HttpResponseBadRequest('Bad content type')
  
  payload = request.read()
  try:
    signature = request.META['X-Hub-Signature'].split('=')[1]
  except KeyError:
    return HttpResponseBadRequest('No signature header received')
  
  hash = hmac.new(settings.FACEBOOK_APP_SECRET, payload, hashlib.sha1).digest()
  if hash != signature:
    return HttpResponseBadRequest('Invalid signature header')
  
  # Process the update
  data = simplejson.loads(payload)
  updated_object = data["object"]
  
  if updated_object == 'permission':
    perms_to_remove = {}
    for change in data['entry']:
      perms_to_remove[change['uid']] = change['changed_fields']
    permissions.remove_permissions_from_users(perms_to_remove)
    
  return HttpResponse('Update Processed Successfully')
      
      
    
    
  